﻿/// <reference path="JSintellisense/jquery-1.3.2-vsdoc2.js" />
var map = null;
var geocoder = null;
var marker = null;
var center = null;
var lat_lng_all = "";
var latlng_array = null;
var gzoom = 14;
var myadd = "";
var initpoint = null;
var myGeo = null;
var mylabel = null;
var adds = null;
var currentlocationObject = 'f';//正在定位的对像，f表示发件，t表示收件，坐标赋值时会根据这个来查询
var city = { "cityid": 0, "cityname": "" };
var cityjson = null;
var feejson = null;
var cityName = "全国";

function initialize() {

    //    handlecookie("mylat", lat, { expires: 30, path: "/", secure: false });

    cityName = "全国";
    function myFun(result) {
        cityName = result.name.replace("市", "");
        queryCity(cityName);
        $("#lbautomyaddress").html(cityName);
    }
    var myCity = new BMap.LocalCity();
    myCity.get(myFun);

    $("#lbautomyaddress").click(function ()
    {
        queryCity(cityName);
    })


    myGeo = new BMap.Geocoder();

    //建立一个自动完成的对象
    ac = new BMap.Autocomplete({ "input": "keyaddress", "location": cityName });
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件



        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;

      

        myGeo.getPoint(myValue, function (point) {
            if (point) {
                setaddress(point.lat, point.lng, myValue, "");
                $("#keyaddress").val("");

            }
        }, cityName);
    });


    geocoder = new BMap.Geocoder();
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            center = r.point;
            initpoint = r.point;
            geocoder.getLocation(r.point, function (rs) {
                var addComp = rs.addressComponents;
                myValue = addComp.city + addComp.district + addComp.street + addComp.streetNumber
                $("#tbAddress").val(myValue);

                setaddress(r.point.lat, r.point.lng, myValue, "");

            });
        }
        else {
            //alert("定位失败" + this.getStatus());
        }
    }, { enableHighAccuracy: true });

}

function queryCity(address) {
    //找出城市
    for (var i in cityjson) {
        if (address.indexOf(cityjson[i].cname) >= 0) {
            selcity(cityjson[i].cname, cityjson[i].cid);
            break;
        }
    }
}

//选择城市
function selcity(cname, cid) {
    city.cityid = cid;
    city.cityname = cname;
    $("#hfcityname").val(city.cityname);
    $(".citynamebox").html(city.cityname);


    //建立一个自动完成的对象
    ac = new BMap.Autocomplete({ "input": "keyaddress", "location": cname });
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件

       // debugger;

        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        console.log(myValue);




        var patrn = /\d+号/; //有具体的门牌号是要用地址解析，否则使用智能搜索
        if (patrn.test(myValue)) {
            myGeo.getPoint(myValue, function (point) {
                if (point) {
                  
                    console.log(point.lat + "," + point.lng);
                    setaddress(point.lat, point.lng, myValue, "");
                    $("#keyaddress").val("");

                }
                else {
                    searchFail();
                }
            }, cname);

        }
        else {

            var local = new BMap.LocalSearch(cname, {
                map: map,
                autoViewport: true,
                selectFirstResult: true,
                onSearchComplete: function (result) {

                   // debugger;

                    if (result != null && result.getPoi(0) != null) {
                        var point = result.getPoi(0).point;
                   
                        console.log(point.lat + "," + point.lng);
                        setaddress(point.lat, point.lng, myValue, "");
                        $("#keyaddress").val("");


                    }
                    else {
                        searchFail();
                    }
                }

            });


            local.search(myValue);
        }



        //myGeo.getPoint(myValue, function (point) {
        //    if (point) {
        //        console.log(point.lat + "," + point.lng);
        //        setaddress(point.lat, point.lng, myValue, "");
        //        $("#keyaddress").val("");

        //    }
        //}, cname);
    });






    $(".mModal").hide();
    $("#remarktip").hide();


}

function searchFail() { 
    alert("未找到相应地址,请重新输入");
}

function setLatLng(point) {
    document.getElementById("lat").value = point.lat;
    document.getElementById("lng").value = point.lng;

    return true;
}

//定位相关类
$(function () {
    var type = request("type");
    if (type == 1) {
        //setexpresstype(this, 1);
        $("#buybtn").click();
    }
    else {
        $("#sendbtn").click();
        //setexpresstype(this, 0);
    }

    cityjson = eval("(" + $("#hfcityjson").val() + ")");
    feejson = eval("(" + $("#hffeesjon").val() + ")");

    initialize();

    $("#maptipbox").hide();

    var screenwidth = document.documentElement.clientWidth;
    var screenheight = document.documentElement.clientHeight

    var maskleft = screenwidth * 0.1 / 2; //弹出层90%，left= screenwidth*10%/2
    $(".freeSet").css({ left: maskleft + "px" });
    $("#mymark").css({ height: screenheight + "px" });

    $(".x,.mModal").click(function () {
        $(".mModal,.mDialog").hide();
    });
    var type = $("input[name='rbordertype']:checked").val();
    if (type == "0") {
        var d = new Date()
        var senttime = d.toLocaleDateString() + " " + d.getHours() + ":" + d.getMinutes();
        $("#tbSentTime").val(senttime);
        calDistanceAndFee();
    }

})


function setPlace() {
    var cityname = $("#hfcityname").val();
    var address = document.getElementById("keyaddress").value;
    searchPlaceOnMap(address);
}

function showmap(address, locationtag) {
    $("#maptipbox").show();
    $(".mModal").show();
    currentlocationObject = locationtag;
    bangdingHistoryAddress();
    searchPlaceOnMap(address);
}

function bangdingHistoryAddress() {
    FromAddress.key = currentlocationObject + "_address";
    $("#addressbox").html($("#addressTemplate").render(FromAddress.getproductlist()));


}

function setaddress(lat, lng, address, door) {
    if (currentlocationObject == "f") {
        $("#tbAddress").val(address);
        $("#tbAddressdetail").val(door);
        queryCity(address);

    }
    else {
        $("#tbOorderid").val(address);
        $("#tbOorderiddetail").val(door);
    }

    setLatLng(new BMap.Point(lng, lat));
    locationComplete();
}

function searchPlaceOnMap(address) {
    if (address.length == 0) {
        //swal("", "请输入地址", "warning");
        return;
    }

    var cityname = $("#hfcityname").val();
    var local = new BMap.LocalSearch(cityname, {
        renderOptions: {
            map: map,
            autoViewport: true,
            selectFirstResult: false
        }
    });
    local.search(address);
}


function locationComplete() {
    var _lat = parseFloat($("#lat").val());
    var _lng = parseFloat($("#lng").val());

    $("#hid" + currentlocationObject + "lat").val(_lat);
    $("#hid" + currentlocationObject + "lng").val(_lng);
    $(".mModal,.mDialog").hide();

    calDistanceAndFee();
    //todo计算距离，配送费。
}

///计算距离，配送费。
function calDistanceAndFee(callback) {
    var flat = $("#hidflat").val();
    var flng = $("#hidflng").val();
    if (flat == 0 || flng == 0) {
        //swal("", "收件地址未定位", "warning");
        console.log("取件地址未定位");
        return;
    }

    var tlat = $("#hidtlat").val();
    var tlng = $("#hidtlng").val();
    if (tlat == 0 || tlng == 0) {
        //swal("", "收件地址未定位", "warning");
        console.log("收件地址未定位");
        return;
    }
    var SentTime = $("#tbSentTime").val() + "";
    if (SentTime.length == 0) {
        console.log("取件时间未定");
        return;
    }
    var orderType = $("#tbcallcount").val();; //0?"送":"买"

    var mydata = "method=expressDistanceAndFee&flat=" + flat + "&flng=" + flng + "&tlat=" + tlat + "&tlng=" + tlng + "&sendtime=" + SentTime + "&cityid=" + city.cityid + "&cityname=" + city.cityname + "&orderType=" + orderType;
    jQuery.ajax(
    {
        type: "get",
        url: "ajaxHandler.ashx",
        cache: false,
        data: mydata,
        success: function (msg) {
            var data = eval("(" + msg + ")");
            console.log(msg);
            if (data.sendmoney < 0) {
                swal("", "此城市尚未开通此服务", "warning");
                $("#btnextstep").hide();
                return;
            }
            $("#btnextstep").show();

            $("#lbdistance").html(data.Distance);
            $("#lbsendfee").html(data.sendmoney);

            $("#hiddistance").val(data.Distance);
            $("#hidsendfee").val(data.sendmoney);

            if (typeof callback != 'undefined') {
                callback();
            }

        }
    })
}

//转到下一步
function nextstep() {
    var flat = $("#hidflat").val();
    var flng = $("#hidflng").val();
    if (flat.length == 0 || flng.length == 0) {
        swal("", "取件地址未定位", "warning");
        return false;;
    }

    var tlat = $("#hidtlat").val();
    var tlng = $("#hidtlng").val();
    if (tlat.length == 0 || tlng.length == 0) {
        swal("", "收件地址未定位", "warning");
        return false;;
    }

    var flag = j_submitdata("orderdetail");
    if (false == flag) {
        return false;
    }

    Loader.show("#btnextstep");


    calDistanceAndFee(gotonext);

    return false;
}

function gotonext() {
    //保存信息 
    for (var key in expressInfo) {
        expressInfo[key] = $("#" + key).val();
    }
    expressInfo.cityid = city.cityid;
    express.saveExpressinfo(expressInfo);

    var url = "expresstwo.aspx";
    window.location.href = url;
    return false;

}

var typeicon = ["送", "买"];

function setexpresstype(target, type) {
    if (type == 1) {
        $("#page_title").find("h1").html("代买");
    }
    else {
        $("#page_title").find("h1").html("代送");
    }
    $(".paotui_con .cur").removeClass("cur");
    $(target).addClass("cur");
    $("#tbcallcount").val(type);;
    $("#typeiconbox").html(typeicon[type]);
}

function shopricetip() {
    if (city.cityid == 0) {
        swal("", "请先确认您的地址", "warning");
        return;
    }
    //根据城市编号获取配送费信息
    for (var i in feejson) {
        if (city.cityid == feejson[i].cityid) {
            feejson[i].revevar3 = city.cityname;



            var tipmsg = $("#priceModule").render(feejson[i]);

            swal({
                title: "计价说明",
                text: tipmsg,
                html: true,

            });
            return;
        }
    }

    swal("", "此城市尚未开通此服务", "warning");



}

/// yyyy-MM-dd HH:mm:ss 转成时间
function StringToDate(DateStr) {

    var datetimes = DateStr.split(" ");

    var date = datetimes[0].split("-");
    var time = datetimes[0].split(":");


    var mydate = new Date(date[0], parseInt(date[1]) - 1, date[2], time[0], time[1], time[2]);;
    return mydate;
}



///选择城市
function showcitybox() {
    $(".mModal").show();
    $("#remarktip").show();
    var clientHeight = document.documentElement.clientHeight;
    $("#remarktip").css({ "margin-top": (-clientHeight * 0.4) + "px" });
}
